/*
 * PrintThread.cpp
 *
 *  Created on: 2021年3月4日
 *      Author: Admin
 */

#include "PrintThread.h"
#include "utils/Log.h"
#include "string.h"
#include "zkdisplay.h"
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_STATIC
#define STBI_NO_PSD
#define STBI_NO_TGA
#define STBI_NO_GIF
#define STBI_NO_HDR
#define STBI_NO_PIC
#define STBI_NO_PNM
#include "stb_image.h"

#define DIE_DELIMTER '/'
#define MAX_FILENAME 512

extern void writefile(const char* filename,unsigned char* pdata,uint32_t len );
PrintThread::PrintThread() {
	// TODO 自动生成的构造函数存根

}

PrintThread::~PrintThread() {
	// TODO 自动生成的析构函数存根
}

bool PrintThread::threadLoop() {

}

bool PrintThread::startPrint(const char* pfile) {

    const char* fn = pfile;
    zipfile = unzOpen(fn);
   	if (zipfile == NULL)
   	{
   		LOGD("%s: not found\n", fn);
   		return false;
   	}
   	if (unzGetGlobalInfo(zipfile, &global_info) != UNZ_OK)
   	{
   		LOGD("could not read zip file global info\n");
   		unzClose(zipfile);
   		return false;
   	}
   	for (int i = 0; i < global_info.number_entry; ++i)
	{
		// Get info about current file.
		unz_file_info file_info;
		char filename[MAX_FILENAME];
		if (unzGetCurrentFileInfo(zipfile, &file_info, filename, MAX_FILENAME, NULL, 0, NULL, 0) != UNZ_OK)
		{
			LOGD("could not read file info\n");
			unzClose(zipfile);
			return false;
		}

		LOGD("file[%s ]filesize cs:%d, us:%d\n",filename, file_info.compressed_size, file_info.uncompressed_size);

		if(strcmp(filename,"run.gcode") == 0){
			LOGD("file:%s\n", filename);
			if (unzOpenCurrentFile(zipfile) != UNZ_OK)
			{
				LOGD("could not open file: %s\n", filename);
				unzClose(zipfile);
				return false;
			}

			LOGD("extract file:%s\n", filename);

			int error = UNZ_OK;
			unsigned char* read_buf = (unsigned char*)malloc(file_info.uncompressed_size);
			error = unzReadCurrentFile(zipfile, read_buf, file_info.uncompressed_size);
			if (error < 0)
			{
				LOGD("error %d\n", error);
				unzCloseCurrentFile(zipfile);
				unzClose(zipfile);
				free(read_buf);
				return false;
			}
			writefile("/mnt/extsd/run.gcode",read_buf, file_info.uncompressed_size);
			//uint8_t *pData = stbi_load_from_memory(read_buf, file_info.uncompressed_size, &width, &height, &depth, 0);
			free(read_buf);
			unzCloseCurrentFile(zipfile);
			return true;
		}

		unzCloseCurrentFile(zipfile);
		// Go the the next entry listed in the zip file.
		if ((i+1) < global_info.number_entry)
		{
			if (unzGoToNextFile(zipfile) != UNZ_OK)
			{
				LOGD("cound not read next file\n");
				unzClose(zipfile);
				return false;
			}
		}
	}

   	return false;

}

int PrintThread::getPrintProgress() {
}

int PrintThread::getReminTime() {
}

int PrintThread::getTotalTime() {
}

const char* PrintThread::getFileName() {
}
